﻿using Microsoft.EntityFrameworkCore;
using TuLing.Dto;
using TuLing.Entities;
using TuLing.IServices;

namespace TuLing.Services
{
    public class ProductUnitService : BaseService, IProductUnitService
    {
        public ProductUnitService(DefaultDbContext context) : base(context) { }

        public async Task<List<UnitDto>> Search(BaseInput input)
        {
            if (!string.IsNullOrEmpty(input.keyword))
            {
                var list = await _context.Units
                    .Where(m => EF.Functions.Like(m.Name, $"%{input.keyword}%"))
                    .OrderBy(m => m.Id)
                    .ToListAsync();
                return list.Select(m => new UnitDto { Id = m.Id, Name = m.Name }).ToList();
            }
            var listAll = await _context.Units.ToListAsync();
            return listAll.Select(m => new UnitDto { Id = m.Id, Name = m.Name }).ToList();
        }

        public async Task Save(UnitDto input)
        {
            var isExist = await _context.Units.AnyAsync(m => m.Name == input.Name && m.Id != input.Id);
            if (isExist)
            {
                throw new Exception("产品单位已经存在了。");
            }

            if (input.Id > 0)
            {                         
                var unit = await _context.Units.FirstOrDefaultAsync(m => m.Id == input.Id);
                if (unit == null)
                {
                    throw new Exception("产品单位不存在。");
                }
                unit.Name = input.Name;
                _context.Units.Update(unit);
                await _context.SaveChangesAsync();             
            }
            else
            {
                var inputUnit = new Unit
                {
                    Name = input.Name
                };
                _context.Units.Add(inputUnit);
                await _context.SaveChangesAsync();
            }
        }

        public async Task Delete(long id)
        {
            var unit = await _context.Units.FirstOrDefaultAsync(m => m.Id == id);
            if (unit == null)
            {
                throw new Exception("产品单位不存在。");
            }
            _context.Units.Remove(unit);
            _context.SaveChanges();
        }
    }
}
